package com.zhike.utils;

import com.alibaba.fastjson.JSONObject;
import com.zhike.constant.HbaseConstant;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.Collection;
import java.util.Set;

/**
 * @Author: zhike
 * @CreateTime: 2024/1/19 13:50
 * @Description: Phoenix表数据插入方法
 */
public class PhoenixUtils {

    private static PreparedStatement preparedStatement;

    public static void  insertValues(Connection connection, String sinkTable, JSONObject data){
        //1.获取字段名
        Set<String> cloumns = data.keySet();

        //2.获取字段值
        Collection<Object> values = data.values();

        //3.拼接字段名
        String columnStr = StringUtils.join(cloumns, ",");
        /**
         * upsert into table_name (column_name1,column_name2,column_name3) values (‘value1’,‘value2’,‘value3’)
         */
        //4.拼接字段值
        String valueStr = StringUtils.join(values, "','");

        //5.拼接sql
        String sql = "upsert into "+ HbaseConstant.HBASE_SCHEMA+"."+sinkTable+" ("+columnStr+") values ('"+valueStr+"')";

        System.out.println("插入sql："+sql);
//        //6.执行sql
        try {
            //预编译sql
            preparedStatement = connection.prepareStatement(sql);
            //执行sql
            preparedStatement.execute();
            //提交事务
            connection.commit();
        } catch (SQLException e) {
            System.out.println("出错了>>>>>");
            throw new RuntimeException(e);
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException("数据库操作对象释放异常");
                }
            }
        }

    }


}
